package com.example.demo.service.impl;

import com.example.demo.entity.User;
import com.example.demo.mapper.UserMapper;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public User register(User user) {
        // 检查用户名是否已存在
        if (userMapper.selectUserByUsername(user.getUsername()) != null) {
            throw new RuntimeException("Username already exists");
        }
        userMapper.insertUser(user);
        return user;
    }

    @Override
    public User login(String username, String password) {
        User user = userMapper.selectUserByUsername(username);
        if (user == null || !user.getPassword().equals(password)) {
            throw new RuntimeException("Invalid username or password");
        }
        return user;
    }

    @Override
    public User getUserById(Long userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    @Transactional
    public User updateUser(User user) {
        userMapper.updateUser(user);
        return userMapper.selectUserById(user.getUserId());
    }

    @Override
    @Transactional
    public void deleteUser(Long userId) {
        userMapper.deleteUser(userId);
    }

    @Override
    @Transactional
    public void followUser(Long followerId, Long followingId) {
        if (followerId.equals(followingId)) {
            throw new RuntimeException("Cannot follow yourself");
        }
        userMapper.addFollower(followingId, followerId);
    }

    @Override
    @Transactional
    public void unfollowUser(Long followerId, Long followingId) {
        userMapper.removeFollower(followingId, followerId);
    }

    @Override
    public List<User> getFollowers(Long userId) {
        List<Long> followerIds = userMapper.selectFollowersByUserId(userId);
        // 这里需要批量查询用户信息，简化示例
        return null;
    }

    @Override
    public List<User> getFollowing(Long userId) {
        List<Long> followingIds = userMapper.selectFollowingByUserId(userId);
        // 这里需要批量查询用户信息，简化示例
        return null;
    }
}